package cs5226.tags;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import cs5226.model.SQLResultSet;

public class SQLResultSetValue extends SimpleTagSupport {
	public final String TD_OPENING = "<td class='TableValue'>";
	public final String TD_OPENING_INCOMPLETE = "<td class='TableValue' ";
	public final String TD_CLOSING = "</td>";
	
	private SQLResultSet sqlresultset;
	
	private String getTDOpeningNoRow(int columnCount){
		return TD_OPENING_INCOMPLETE + "colspan='" + columnCount + "'> No result available" + TD_CLOSING;
		
	}
	
	@Override
	public void doTag() throws JspException, IOException {
		if (sqlresultset == null) {
			getJspContext().getOut().println (TD_OPENING + "No result set found" + TD_CLOSING);
			return;
		}
		
		try {
			ArrayList<ArrayList<String>> data = sqlresultset.getData();
			
			JspWriter out = getJspContext().getOut();
			
			//loop through rows
			for (int j=0;j<data.size();j++)
			{
				out.println("<tr>");
				
				ArrayList<String> row = data.get(j);
				//loop through columns
				for (int i=0; i<row.size(); i++){
					String value = row.get(i);
					out.println (TD_OPENING + value + TD_CLOSING);
				}
				
				out.println("</tr>");
			}			
		} catch (Exception e) {
			e.printStackTrace();
			getJspContext().getOut().println (TD_OPENING + "Exception: " + e.getMessage() + TD_CLOSING);			
		}
		
	}

	public SQLResultSet getSqlresultset() {
		return sqlresultset;
	}

	public void setSqlresultset(Object value) {
		if (value instanceof SQLResultSet) {
			this.sqlresultset = (SQLResultSet) value;
		}
		else this.sqlresultset = null;
	}
}
